//
//  WithdrawRecordViewController.m
//  HWZB
//
//  Created by 许成雄 on 2017/4/23.
//  Copyright © 2017年 wonders. All rights reserved.
//

#import "WithdrawRecordViewController.h"
#import "HACursor.h"
#import "WithdrawRecordTableViewCell.h"
#import "WithdrawRecordInfo.h"
#import "HWZBAPIRequest.h"
#import "Context.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import "MBProgressHUD+Toast.h"

@interface WithdrawRecordViewController () <UITableViewDelegate, UITableViewDataSource, HACursorDelegate>

@property (strong, nonatomic) HACursor *mHACursor;
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *typeArray;
@property (strong, nonatomic) NSMutableArray *withdrawRecordArray;
@property (assign, nonatomic) NSInteger selectIndex;

@end

@implementation WithdrawRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = I_COLOR_BACKGROUND;
    [self setBackNavgationItem];
    self.navigationItem.title = @"提现记录";
    self.selectIndex = 0;
    
    [self loadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - UITableViewDelegate && UITableViewDatasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger count = self.withdrawRecordArray != nil ? self.withdrawRecordArray.count : 0;
    return count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = TRANS_VALUE(70.0f);
    return height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    CGFloat height = 0.0f;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, height)];
    view.backgroundColor = RGBCOLOR(247, 247, 247);
    return view;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"WithdrawRecordTableViewCell";
    WithdrawRecordTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(!cell) {
        cell = [[WithdrawRecordTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
    }
    if(indexPath.row < [self.withdrawRecordArray count]) {
        //TOOD -- 发现列表
        WithdrawRecordInfo *recordInfo = (WithdrawRecordInfo *)[self.withdrawRecordArray objectAtIndex:indexPath.row];
        cell.withdrawRecordInfo = recordInfo;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.row < self.withdrawRecordArray.count) {
        if([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:UIEdgeInsetsZero];
        }
        if([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:UIEdgeInsetsZero];
        }
    } else {
        if([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:UIEdgeInsetsZero];
        }
        if([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:UIEdgeInsetsZero];
        }
    }
}

#pragma mark - HACursorDelegate
- (void)cursor:(HACursor *)cursor selectedAtIndex:(NSInteger)index {
    if(index == self.selectIndex) {
        return;
    }
    if(index < [self.typeArray count]) {
        //TODO -- 刷新tableview
        NSLog(@"刷新第%ld个tableview....", (long)index);
        self.selectIndex = index;
        //刷新tableview
        [self loadTableData];
    }
}

#pragma mark - Private Method
- (void)createUI {
    self.mHACursor = [[HACursor alloc] init];
    self.mHACursor.frame = CGRectMake(0, 0, SCREEN_WIDTH, TRANS_VALUE(34));
    self.mHACursor.titles = self.typeArray;
    self.mHACursor.pageViews = [self createPageViews];
    //设置根滚动视图的高度
    if(SCREEN_WIDTH == 320 && SCREEN_HEIGHT <= 568) {
        self.mHACursor.rootScrollViewHeight = SCREEN_HEIGHT - 20.0f - TRANS_VALUE(80.0f);
    } else {
        self.mHACursor.rootScrollViewHeight = SCREEN_HEIGHT - 10.0f - TRANS_VALUE(80.0f);
    }
    
    self.mHACursor.backgroundColor = I_COLOR_WHITE;
    //默认值是白色
    self.mHACursor.titleNormalColor = I_COLOR_33BLACK;
    //默认值是白色
    self.mHACursor.titleSelectedColor = I_COLOR_RED;
    //是否显示排序按钮
    self.mHACursor.showSortbutton = NO;
    //默认的最小值是5，小于默认值的话按默认值设置
    self.mHACursor.minFontSize = TRANS_VALUE(14.0f);
    //默认的最大值是25，小于默认值的话按默认值设置，大于默认值按设置的值处理
    //cursor.maxFontSize = 30;
    //cursor.isGraduallyChangFont = NO;
    //在isGraduallyChangFont为NO的时候，isGraduallyChangColor不会有效果
    //cursor.isGraduallyChangColor = NO;
    [self.view addSubview:self.mHACursor];
    
    self.mHACursor.delegate = self;
}

- (NSMutableArray *)createPageViews {
    NSMutableArray *pageViews = [NSMutableArray array];
    for (NSInteger i = 0; i < self.typeArray.count; i++) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - TRANS_VALUE(34.0f))];
        view.backgroundColor = I_COLOR_BACKGROUND;
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, TRANS_VALUE(5.0f), SCREEN_WIDTH, SCREEN_HEIGHT - 64.0f - TRANS_VALUE(34.0f) - TRANS_VALUE(5.0f))];
        [view addSubview:tableView];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = I_COLOR_WHITE;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        //        // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
        //        MyRefreshHeader *header = [MyRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        //        tableView.mj_header = header;
        //
        //        // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
        //        MyRefreshFooter *footer = [MyRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        //        tableView.mj_footer = footer;
        
        [tableView registerClass:[WithdrawRecordTableViewCell class] forCellReuseIdentifier:@"WithdrawRecordTableViewCell"];
        
        view.tag = i + 10000;
        [pageViews addObject:view];
    }
    return pageViews;
}

- (void)loadData {
    [self loadTypeInfo];
}

- (void)loadTypeInfo {
    if(!self.typeArray) {
        self.typeArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    [self.typeArray removeAllObjects];
    [self.typeArray addObjectsFromArray:@[@"全部", @"提现中", @"已完成"]];
    [self createUI];
    [self loadTableData];
}

- (void)loadTableData {
    if(!self.withdrawRecordArray) {
        self.withdrawRecordArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    [self.withdrawRecordArray removeAllObjects];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
    [SVProgressHUD showWithStatus:@"正在获取提现记录..." maskType:SVProgressHUDMaskTypeClear];
    [[HWZBAPIRequest sharedInstance] getWithdrawRecordsWithParams:params success:^(NSArray *recordArray) {
        [SVProgressHUD dismiss];
        if(recordArray) {
            [self sortCommodityList:recordArray];
        }
        UIView *view = (UIView *)[self.view viewWithTag:(self.selectIndex + 10000)];
        UITableView *tableView = (UITableView *)[view.subviews objectAtIndex:0];
        [tableView reloadData];
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
        NSLog(@"%@", [error localizedDescription]);
        UIView *view = (UIView *)[self.view viewWithTag:(self.selectIndex + 10000)];
        UITableView *tableView = (UITableView *)[view.subviews objectAtIndex:0];
        [tableView reloadData];
    }];
}

- (void)sortCommodityList:(NSArray *)recordList {
    if(self.selectIndex == 0) {
        [self.withdrawRecordArray addObjectsFromArray:recordList];
    } else {
        NSString *state = nil;
        if(self.selectIndex == 1 ) {
            state = @"0";
        } else if(self.selectIndex == 2) {
            state = @"1";
        } 
        for(int i = 0, n = (int)recordList.count; i < n; i++) {
            WithdrawRecordInfo *recordInfo = (WithdrawRecordInfo *)[recordList objectAtIndex:i];
            if([state isEqualToString:@"1"] && [recordInfo.state isEqualToString:state]) {
                [self.withdrawRecordArray addObject:recordInfo];
            } else if([state isEqualToString:@"0"] && ![recordInfo.state isEqualToString:@"1"]) {
                [self.withdrawRecordArray addObject:recordInfo];
            }
        }
    }
}

@end
